<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { useUserStoreHook } from "@/store/modules/user";
import { ElMessage } from "element-plus";
import { IconifyIconOffline } from "@/components/ReIcon";
import StatsCard from "./components/StatsCard.vue";
import TrendChart from "./components/TrendChart.vue";
import ActivityStats from "./components/ActivityStats.vue";
import {
  getDashboardDataApi,
  type DashboardData,
  type TodayStats,
  type ActivityStats as ActivityStatsType,
  type GrowthTrendStats
} from "@/api/dashboard";

defineOptions({
  name: "Welcome"
});

const userStore = useUserStoreHook();

// 响应式数据
const loading = ref(false);
const dashboardData = ref<DashboardData | null>(null);
const lastUpdateTime = ref<string>("");

// 计算属性
const todayStats = computed(() => dashboardData.value?.todayStats || null);
const activityStats = computed(
  () => dashboardData.value?.activityStats || null
);
const growthTrendStats = computed(
  () => dashboardData.value?.growthTrendStats || null
);

// 用户信息
const userInfo = computed(() => ({
  username: userStore.username,
  roles: userStore.roles
}));

// 获取仪表盘数据
const fetchDashboardData = async () => {
  try {
    loading.value = true;
    console.log("开始获取仪表盘数据...");

    const response = await getDashboardDataApi();
    console.log("仪表盘数据响应:", response);

    if (response.code === 200 && response.data) {
      dashboardData.value = response.data;
      lastUpdateTime.value = new Date().toLocaleString();
      ElMessage.success("仪表盘数据加载成功");
    } else {
      throw new Error(response.message || "获取仪表盘数据失败");
    }
  } catch (error) {
    console.error("获取仪表盘数据失败:", error);
    ElMessage.error("获取仪表盘数据失败，请稍后重试");
  } finally {
    loading.value = false;
  }
};

// 刷新数据
const refreshData = () => {
  fetchDashboardData();
};

// 组件挂载时获取数据
onMounted(() => {
  fetchDashboardData();
});
</script>

<template>
  <div class="dashboard-container">
    <!-- 页面头部 -->
    <div class="dashboard-header">
      <div class="header-content">
        <div class="welcome-info">
          <h1>欢迎回来，{{ userInfo.username }}！</h1>
          <p class="welcome-subtitle">
            今天是 {{ new Date().toLocaleDateString() }}，祝您工作愉快！
          </p>
        </div>
        <div class="header-actions">
          <el-button type="primary" :loading="loading" @click="refreshData">
            <IconifyIconOffline icon="ep:refresh" class="mr-1" />
            刷新数据
          </el-button>
        </div>
      </div>
      <div v-if="lastUpdateTime" class="update-time">
        最后更新时间：{{ lastUpdateTime }}
      </div>
    </div>

    <!-- 今日新增统计 -->
    <div class="stats-section">
      <h2 class="section-title">今日新增统计</h2>
      <el-row v-loading="loading" :gutter="24">
        <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
          <StatsCard
            title="新增用户"
            :value="todayStats?.newUsers || 0"
            icon="ep:user-filled"
            icon-color="#409EFF"
            :growth-rate="todayStats?.userGrowthRate || 0"
            compare-text="较昨日"
          />
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
          <StatsCard
            title="新增文章"
            :value="todayStats?.newArticles || 0"
            icon="ep:document"
            icon-color="#67C23A"
            :growth-rate="todayStats?.articleGrowthRate || 0"
            compare-text="较昨日"
          />
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
          <StatsCard
            title="新增评论"
            :value="todayStats?.newComments || 0"
            icon="ep:chat-line-round"
            icon-color="#E6A23C"
            :growth-rate="todayStats?.commentGrowthRate || 0"
            compare-text="较昨日"
          />
        </el-col>
      </el-row>
    </div>

    <!-- 平台活跃度和增长趋势 -->
    <div class="charts-section">
      <el-row :gutter="24">
        <el-col :xs="24" :sm="24" :md="12" :lg="8" :xl="8">
          <ActivityStats :data="activityStats" />
        </el-col>
        <el-col :xs="24" :sm="24" :md="12" :lg="16" :xl="16">
          <TrendChart
            title="内容增长趋势"
            :data="growthTrendStats"
            :loading="loading"
          />
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<style scoped>
/* 响应式设计 */
@media (width <= 768px) {
  .dashboard-container {
    padding: 16px;
  }

  .dashboard-header {
    padding: 24px 20px;
  }

  .header-content {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }

  .welcome-info h1 {
    font-size: 24px;
  }

  .welcome-subtitle {
    font-size: 14px;
  }

  .update-time {
    text-align: left;
  }

  .section-title {
    font-size: 18px;
  }
}

@media (width <= 480px) {
  .dashboard-header {
    padding: 20px 16px;
  }

  .welcome-info h1 {
    font-size: 20px;
  }

  .section-title {
    font-size: 16px;
  }
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .dashboard-container {
    background: #1a1a1a;
  }

  .section-title {
    color: #e5e7eb;
  }
}

.dashboard-container {
  min-height: calc(100vh - 84px);
  padding: 24px;
  background: #f5f7fa;
}

/* 页面头部 */
.dashboard-header {
  padding: 32px;
  margin-bottom: 24px;
  color: white;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgb(102 126 234 / 30%);
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.welcome-info h1 {
  margin: 0 0 8px;
  font-size: 28px;
  font-weight: 600;
  color: white;
}

.welcome-subtitle {
  margin: 0;
  font-size: 16px;
  color: white;
  opacity: 0.9;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.update-time {
  font-size: 14px;
  color: white;
  text-align: right;
  opacity: 0.8;
}

/* 统计区域 */
.stats-section {
  margin-bottom: 24px;
}

.section-title {
  display: flex;
  align-items: center;
  margin: 0 0 16px;
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.section-title::before {
  width: 4px;
  height: 20px;
  margin-right: 12px;
  content: "";
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 2px;
}

/* 图表区域 */
.charts-section {
  margin-bottom: 24px;
}

/* 加载状态优化 */
.el-loading-mask {
  border-radius: 12px;
}

/* 卡片间距优化 */
.el-row {
  margin-right: -12px !important;
  margin-left: -12px !important;
}

.el-col {
  padding-right: 12px !important;
  padding-left: 12px !important;
  margin-bottom: 24px;
}
</style>
